/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.multishop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.Category;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.i18n.LanguageEnum;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.CategoryService;
import com.yami.shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 分类管理
 * @author lgh
 *
 */
@RestController
@RequestMapping("/prod/category")
public class CategoryController {

	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ProductService productService;


	/**
	 * 获取分类信息
	 */
	@GetMapping("/info/{categoryId}")
	public ResponseEntity<Category> info(@PathVariable("categoryId") Long categoryId){
		// 获取数据库中的分类，如果分类为空则抛异常
		Category category = categoryService.getCategoryByCategoryIdAndShopId(categoryId, SecurityUtils.getShopUser().getShopId());

		return ResponseEntity.ok(category);
	}

	/**
	 * 保存分类
	 */
	@SysLog("保存分类")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('prod:category:save')")
	public ResponseEntity<Void> save(@RequestBody Category category){
		category.setShopId(SecurityUtils.getShopUser().getShopId());
		category.setRecTime(new Date());
//		Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName())
//				.eq(Category::getShopId,category.getShopId()))
		Integer count = categoryService.getCategoryName(category);
		if(count > 0){
//			throw new YamiShopBindException("类目名称已存在！");
			throw new YamiShopBindException("yami.category.name.exist");
		}
		categoryService.saveCategroy(category);
		categoryService.removeCacheByParentIdAndLang(category.getParentId(),category.getShopId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), category.getShopId(), LanguageEnum.LANGUAGE_EN.getLang());
		return ResponseEntity.ok().build();
	}

	/**
	 * 更新分类
	 */
	@SysLog("更新分类")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('prod:category:update')")
	public ResponseEntity<String> update(@RequestBody Category category){
		// 获取数据库中的分类，如果分类为空则抛异常
		categoryService.getCategoryByCategoryIdAndShopId(category.getCategoryId(),SecurityUtils.getShopUser().getShopId());
		category.setShopId(SecurityUtils.getShopUser().getShopId());
		Category categoryDb = categoryService.getById(category.getCategoryId());
		if (Objects.equals(categoryDb.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(category.getParentId(), Constant.CATEGORY_ID)){
			// 一级分类不能改为二级分类
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.one.check"));
		}else if(Objects.equals(category.getParentId(), Constant.CATEGORY_ID) && !Objects.equals(categoryDb.getParentId(), Constant.CATEGORY_ID)){
			// 二级分类不能改为一级分类
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.two.check"));
		}
		if (Objects.equals(category.getParentId(),category.getCategoryId())) {
			// 分类的上级不能是自己本身
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.superior.check"));
		}
		Category categoryName = categoryService.getOne(new LambdaQueryWrapper<Category>().eq(Category::getCategoryName,category.getCategoryName())
														.eq(Category::getShopId,category.getShopId()).ne(Category::getCategoryId,category.getCategoryId()));
		if(categoryName != null){
			// 类目名称已存在!
			throw new YamiShopBindException("yami.category.name.exist");
		}
		category.setOldCategoryName(categoryDb.getCategoryName());
		categoryService.updateCategroy(category);
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), category.getShopId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), category.getShopId(), LanguageEnum.LANGUAGE_EN.getLang());
		return ResponseEntity.ok().build();
	}

	/**
	 * 删除分类
	 */
	@SysLog("删除分类")
	@DeleteMapping("/{categoryId}")
	@PreAuthorize("@pms.hasPermission('prod:category:delete')")
	public ResponseEntity<String> delete(@PathVariable("categoryId") Long categoryId){
		int categoryProdCount = productService.count(new LambdaQueryWrapper<Product>().eq(Product::getShopCategoryId, categoryId).ne(Product::getStatus, -1));
		if (categoryProdCount>0){
			// 该分类下还有商品，请先删除该分类下的商品
			return ResponseEntity.badRequest().body(I18nMessage.getMessage("yami.category.delete.check"));
		}

		Category category = categoryService.getCategoryByCategoryIdAndShopId(categoryId,SecurityUtils.getShopUser().getShopId());
		categoryService.deleteCategroy(category);
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), category.getShopId(), LanguageEnum.LANGUAGE_ZH_CN.getLang());
		categoryService.removeCacheByParentIdAndLang(category.getParentId(), category.getShopId(), LanguageEnum.LANGUAGE_EN.getLang());
		return ResponseEntity.ok().build();
	}

	/**
	 * 获取一级分类
	 */
	@GetMapping("/listCategory")
	public ResponseEntity<List<Category>> listCategory(Category category){
		category.setLang(I18nMessage.getLang());
		category.setGrade(1);
		category.setShopId(SecurityUtils.getShopUser().getShopId());
		List<Category> list =  categoryService.categoryList(category);
		return ResponseEntity.ok(list);
	}

	/**
	 * 平台的分类
	 */
	@GetMapping("/platformCategory")
	public ResponseEntity<List<Category>> listCategory(@RequestParam Integer maxGrade){
		List<Category> list =  categoryService.listByLang(I18nMessage.getLang(),maxGrade,null, 1, Constant.PLATFORM_SHOP_ID);
		return ResponseEntity.ok(list);
	}

}
